﻿<!DOCTYPE html>
<html>
<head> 
	<title>Emitters with Processing.js</title> 
    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script> 
	<script type="text/javascript" src="js/processing.js"></script> 
</head>
<body>
<canvas id="display"></canvas> 

<script  data-processing-target="display" type="application/processing"> 
int totalParticles = 100;
Particle[] particles = new Particle[totalParticles];

float targetX = 0.0;
float targetY = 0.0;

int width, height;

void setup() {
    width = jQuery(document).width() - 30;
    height = jQuery(document).height() - 30;
    size(width, height);
    noStroke();
    smooth();
    background(0);
    for (int i = 0; i < totalParticles; i++) {
        Particle particle = new Particle();
        particles[i] = particle;
    }
};

void draw() {
    fill(color(0, 0, 0, 20));
    rect(0, 0, width, height);

    for (int i = 0; i < totalParticles; i++) {
        particles[i].update();
        particles[i].render();
    }
};

int particleIndex = 0;


//void mouseMoved(){
//    targetX += (mouseX - targetX) * .2;
//    targetY += (mouseY - targetY) * .2;
//    Particle nextParticle = particles[particleIndex];
//    nextParticle.reset(targetX, targetY);
//    if (++particleIndex >= particles.length) particleIndex = 0;
//}

void pointerMove(PointerEvent e) {
    targetX += (e.offsetX - targetX) * .2;
    targetY += (e.offsetY - targetY) * .2;
    var nextParticle = particles[particleIndex];
    nextParticle.reset(targetX, targetY);
    if (++particleIndex >= particles.length) particleIndex = 0;
}

class Particle {
  float x = 0.0;
  float y = 0.0;
  float vx = 0.0;
  float vy = 0.0;
  float r = 255;
  float g = 255;
  float b = 255;
  float a = 255;
  color pColor = color(255, 255, 255, 255);
  int life = 0;

  void update() {
    if (this.life > 0) {
        this.life--;
        if (this.life < 50) {
            this.x += this.vx;
            this.y += this.vy;
            this.vx += random(4) - 2;
            this.vy += random(4) - 2;
            this.vx *= .9;
            this.vy *= .9;
            this.a = 255 * (this.life / 50.0);
        }
    }
  }
  
  void reset(float _x, float _y) {
      this.x = _x;
      this.y = _y;
      this.vx = random(4) - 2;
      this.vy = random(4) * 4 - 2;
      this.life = 150;
      this.g = map(_x, 0, width, 0, 255);
      this.b = map(_y, 0, height, 0, 255);
      this.a = 255;
  }

  void render(){
      fill(color(this.r, this.g, this.b, this.a));
      ellipse(this.x, this.y, 15, 15);
  }
}
	</script> 
    </body>
</html>